import ProForm, {
  ModalForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, message, Popconfirm } from 'antd';
import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import React, { useRef, useState } from 'react';
import { formatTime } from '@/common/publicFun';
import {
  createNewAccount,
  froozen,
  getAllAccount,
  whiteList,
} from '@/service/account';

export default function AccountContent() {
  const actionRef = useRef<ActionType>();
  const restFormRef = useRef<ProFormInstance>();

  const columns: ProColumns[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
      hideInSearch: true,
      width: 80,
      align: 'left',
      fixed: 'left',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      width: 100,
      ellipsis: true,
      // hideInSearch: true,
      align: 'left',
    },
    {
      title: '电话号码',
      width: 108,
      dataIndex: 'account',
      hideInSearch: true,
    },
    {
      title: '注册时间',
      align: 'center',
      dataIndex: 'createAt',
      width: 150,
      hideInSearch: true,
      sorter: (a, b) => {
        return Number(a.createAt) - Number(b.createAt);
      },
      render: (_, _record) => (
        <span>{formatTime(_record.createAt, 'FULL_TIME')}</span>
      ),
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 60,
      align: 'center',
      valueEnum: {
        male: { text: '男' },
        female: { text: '女' },
        '': { text: '未知' },
        secret: { text: '未知' },
      },
    },
    {
      title: '城市',
      width: 100,
      align: 'center',
      dataIndex: 'city',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      width: 60,
      align: 'center',
      hideInSearch: true,
      sorter: (a, b) => {
        return a.age - b.age;
      },
    },
    {
      title: '账号级别',
      dataIndex: 'role',
      width: 80,
      align: 'left',
      valueEnum: {
        normal: { text: '普通用户' },
        specail: { text: '管理员' },
      },
    },
    {
      title: '积分',
      dataIndex: 'score',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '是否会员',
      dataIndex: 'vip',
      width: 80,
      align: 'center',
      valueEnum: {
        true: { text: '是' },
        false: { text: '否' },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      align: 'center',
      editable: false,
      valueEnum: {
        1: { text: '正常', color: 'green' },
        0: { text: '异常', color: 'yellow' },
      },
    },
    {
      title: '操作',
      align: 'center',
      // width: 300,
      key: 'option',
      fixed: 'right',
      valueType: 'option',
      render: (_, _record, index, action) => [
        <Button
          disabled={_record.froozen}
          style={{ borderStyle: 'none', color: '#1890ff' }}
          key={'putWhiteList' + _record.id}
          onClick={() => putIntoWhiteList({ id: _record.id })}
        >
          {_record.inWhiteList ? '移出白名单' : '加入白名单'}
        </Button>,
        <Button
          disabled={_record.inWhiteList}
          style={{ borderStyle: 'none', color: '#1890ff' }}
          key={'froozen' + _record.content + index}
          onClick={() => {
            setFroozen({ id: _record.id });
          }}
        >
          {_record.froozen ? '解冻' : '冻结'}
        </Button>,
      ],
    },
  ];

  async function putIntoWhiteList(params: { id: string }) {
    const data = await whiteList(params);
    if (data.stat === 'ok') {
      message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } else {
      message.error('操作失败，' + data.msg);
    }
  }

  async function setFroozen(params: { id: string }) {
    const data = await froozen(params);
    if (data.stat === 'ok') {
      message.success('操作成功');
      actionRef.current?.reload();
      return true;
    } else {
      message.error('操作失败，' + data.msg);
    }
  }

  return (
    <React.Fragment>
      <ProTable
        actionRef={actionRef}
        pagination={{ pageSize: 7, current: 1, showSizeChanger: true }}
        columns={columns}
        rowKey={'id'}
        search={{ defaultCollapsed: false }}
        request={async (params, sorter, filter) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          const data = await getAllAccount({
            ...params,
            vip:
              params.vip === 'true'
                ? true
                : params.vip === 'false'
                ? false
                : undefined,
            nickname: params.nickname,
            offset: (params.pageSize || 7) * ((params.current || 1) - 1),
            limit: params.pageSize || 7,
            status:
              params.status === '0' ? 0 : params.status === '1' ? 1 : undefined,
            ...sorter,
          });
          return data.data;
        }}
        toolBarRender={() => [
          <ModalForm<{ account: string; nickname: string; password: string }>
            formRef={restFormRef}
            title="新建内部账号"
            trigger={
              <Button type="primary">
                <PlusOutlined />
                新建内部账号
              </Button>
            }
            autoFocusFirstInput
            submitTimeout={2000}
            onFinish={async (value) => {
              const data = await createNewAccount(value);
              if (data.stat === 'ok') {
                message.success('操作成功');
                restFormRef.current?.resetFields();
                actionRef.current?.reload();
                return true;
              } else {
                message.error('操作失败，' + data.msg);
              }
            }}
          >
            <ProForm.Group>
              <ProFormText
                width="lg"
                name="nickname"
                label="昵称"
                placeholder="请输入内容"
              />
            </ProForm.Group>
            <ProForm.Group>
              <ProFormText
                width="lg"
                name="account"
                label="账号"
                placeholder="请输入内容"
              />
              <ProFormText
                width="lg"
                name="password"
                label="密码"
                placeholder="请输入内容"
              />
            </ProForm.Group>
          </ModalForm>,
        ]}
      />
    </React.Fragment>
  );
}
